package com.zjdiepu.www.manage.api.yw;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.zjdiepu.www.base.BaseController;
import com.zjdiepu.www.base.annotation.Add;
import com.zjdiepu.www.base.annotation.Update;
import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.PageVo;
import com.zjdiepu.www.base.enums.status.LoanEditStatus;
import com.zjdiepu.www.base.enums.type.DataDicType;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.commpent.mapper.yw.AbstractYwBusinessLoanVoNewMapper;
import com.zjdiepu.www.commpent.mapper.yw.YwBusinessCarVoMapper;
import com.zjdiepu.www.commpent.mapper.yw.YwBusinessVoMapper;
import com.zjdiepu.www.commpent.mapper.yw.YwFeesVoMapper;
import com.zjdiepu.www.ibiz.cache.ICachedDictionaryService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessCarService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessLoanEditService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessLoanService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessService;
import com.zjdiepu.www.ibiz.yw.IYwFeesService;
import com.zjdiepu.www.model.base.dto.SimpleDataDictionary;
import com.zjdiepu.www.model.yw.dto.YwBusinessCar;
import com.zjdiepu.www.model.yw.dto.YwBusinessLoan;
import com.zjdiepu.www.model.yw.dto.YwBusinessLoanEdit;
import com.zjdiepu.www.model.yw.dto.YwFees;
import com.zjdiepu.www.model.yw.ext.YwBusinessCarExt;
import com.zjdiepu.www.model.yw.ext.YwBusinessLoanExt;
import com.zjdiepu.www.model.yw.response.YwBusinessDetail;
import com.zjdiepu.www.model.yw.response.YwBusinessInfoResponse;
import com.zjdiepu.www.util.ExceptionHelper;

/**
 * 贷款信息Controller层<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年04月24日 10时50分<br/>
 * @since 1.0<br/>
 */
@RestController
@RequestMapping(value= "YwBusinessLoanController", produces="application/json;charset=UTF-8")
@Api(tags = {"贷款信息"}, produces="application/json;charset=UTF-8")
public class YwBusinessLoanController extends BaseController {
    @Resource
    private IYwBusinessLoanService ywBusinessLoanService;
    @Resource
    private IYwBusinessService ywBusinessService;
    @Resource
	private ICachedDictionaryService cachedDictionaryService;
    @Resource
    private YwBusinessVoMapper ywBusinessVoMapper;
    @Resource
    private IYwBusinessCarService ywBusinessCarService;
    @Resource
    private YwBusinessCarVoMapper ywBusinessCarVoMapper;
    @Resource
    private AbstractYwBusinessLoanVoNewMapper ywBusinessLoanVoMapper;
    @Resource
    private IYwBusinessLoanEditService ywBusinessLoanEditService;
    @Resource
    private IYwFeesService ywFeesService;
    @Resource
    private YwFeesVoMapper ywFeesVoMapper;

    /**
     * @author xiongxiaotun <br/>
     * @Title: save  <br/>
     * @Description: 新增贷款信息 <br/>
     * @param ywBusinessLoan
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "新增贷款信息", response = YwBusinessLoan.class, httpMethod="POST", tags={"新增"})
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public ApiResponse save(@Validated(Add.class) @ModelAttribute YwBusinessLoan ywBusinessLoan) {
    	AbstractSysUser currentUser = getCurrentUser();
    	
    	ApiResponse checkIfNeedCalculationResult = ywBusinessLoanService.checkIfNeedCalculation(ywBusinessLoan);
    	String id = null;
    	if(ResultFlagType.SUCCESS.getCode().equals(checkIfNeedCalculationResult.getFlag())) { //需要再计算贷款
    		id = (String)checkIfNeedCalculationResult.getResult();
    	} else {
    		return checkIfNeedCalculationResult; //不需要再计算贷款
    	}
    	ywBusinessLoanService.calculation(ywBusinessLoan);
    	ywBusinessLoan.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	ywBusinessLoan.setModifierName(currentUser.getName());
    	
    	if(StringUtils.isNotBlank(id)) {
    		ywBusinessLoan.setId(id);
    		ywBusinessLoanService.saveUpdateAndDelete(ywBusinessLoan, OperateType.edit);
    	} else {
    		ywBusinessLoanService.saveUpdateAndDelete(ywBusinessLoan, OperateType.add);
    	}
        return ApiResponse.success(ywBusinessLoan);
    }

    @ApiOperation(value = "按公式计算不保存数据库", response = YwBusinessLoan.class, httpMethod="POST", tags={"新增"})
    @RequestMapping(value = "saveWithOut", method = RequestMethod.POST)
    public ApiResponse saveWithOut(@Validated(Add.class) @ModelAttribute YwBusinessLoan ywBusinessLoan) {
    	getCurrentUser();
    	ywBusinessLoanService.calculation(ywBusinessLoan);
        return ApiResponse.success(ywBusinessLoan);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: remove  <br/>
     * @Description: 删除贷款信息<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "删除贷款信息", response = Boolean.class, httpMethod="POST", tags={"删除"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "remove", method = RequestMethod.POST)
    public ApiResponse remove(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	YwBusinessLoan ywBusinessLoan = new YwBusinessLoan();
    	ywBusinessLoan.setId(id);
        ywBusinessLoanService.saveUpdateAndDelete(ywBusinessLoan, OperateType.delete);
        return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: modify  <br/>
     * @Description: 修改贷款信息 <br/>
     * @param ywBusinessLoan
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "修改贷款信息", response = YwBusinessLoan.class, httpMethod="POST", tags={"修改"})
    @RequestMapping(value = "modify", method = RequestMethod.POST)
    public ApiResponse modify(@Validated(Update.class) @ModelAttribute YwBusinessLoan ywBusinessLoan) {
    	AbstractSysUser currentUser = getCurrentUser();
    	ApiResponse checkIfNeedCalculationResult = ywBusinessLoanService.checkIfNeedCalculation(ywBusinessLoan);
    	String id = null;
    	if(ResultFlagType.SUCCESS.getCode().equals(checkIfNeedCalculationResult.getFlag())) { //需要再计算贷款
    		id = (String)checkIfNeedCalculationResult.getResult();
    	} else {
    		return checkIfNeedCalculationResult; //不需要再计算贷款
    	}
    	ywBusinessLoanService.calculation(ywBusinessLoan);
    	ywBusinessLoan.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	ywBusinessLoan.setModifierName(currentUser.getName());
    	
    	if(StringUtils.isNotBlank(id)) {
    		ywBusinessLoan.setId(id);
    		ywBusinessLoanService.saveUpdateAndDelete(ywBusinessLoan, OperateType.edit);
    	} else {
    		ywBusinessLoanService.saveUpdateAndDelete(ywBusinessLoan, OperateType.add);
    	}
        return ApiResponse.success(ywBusinessLoan);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: getById  <br/>
     * @Description: 主键查询贷款信息<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "主键查询贷款信息", response = YwBusinessLoan.class, httpMethod="POST", tags={"主键查询"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "getById", method = RequestMethod.POST)
    public ApiResponse getById(String id){
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
       YwBusinessLoan ywBusinessLoan = ywBusinessLoanService.selectById(id);
       if(null == ywBusinessLoan) {
    	   return ApiResponse.fail(ResultFlagType.MISSING);
       }
       return ApiResponse.success(ywBusinessLoan);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: list  <br/>
     * @Description: 条件查询贷款信息 <br/>
     * @param ywBusinessLoanExt
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "条件查询贷款信息",response = YwBusinessLoan.class, httpMethod="POST", tags={"列表"})
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public ApiResponse list(@ModelAttribute YwBusinessLoanExt ywBusinessLoanExt){
        ywBusinessLoanExt.notDeleted();
        PageVo page = getPage(ywBusinessLoanExt);
        int records = ywBusinessLoanService.countByExt(ywBusinessLoanExt);
        page.setRecords(records);
        if (records > 0) {
            List<YwBusinessLoan> dpBaseDataDictionaries = ywBusinessLoanService.selectByExt(ywBusinessLoanExt);
            page.setRows(dpBaseDataDictionaries);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }
    
    @ApiOperation(value = "条件查询贷款信息",response = YwBusinessInfoResponse.class, httpMethod="POST", tags={"列表"})
    @RequestMapping(value = "getMultiById", method = RequestMethod.POST)
	public ApiResponse getMultiById(String id) {
		if (StringUtils.isBlank(id)) {
			return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
		}
		YwBusinessInfoResponse response = new YwBusinessInfoResponse();
		List<SimpleDataDictionary> loanBanks = cachedDictionaryService.getCachedDataDics(DataDicType.LOAN_BANK);
		response.setLoanBanks(loanBanks);
		
		List<SimpleDataDictionary>  intTypes = cachedDictionaryService.getCachedDataDics(DataDicType.INT_TYPE);
		response.setIntTypes(intTypes);
		
		List<SimpleDataDictionary>  carTypes = cachedDictionaryService.getCachedDataDics(DataDicType.CAR_TYPE);
		response.setCarTypes(carTypes);
		
		YwBusinessDetail ywBusinessDetail = ywBusinessService.getMultiById(id);
		if (null == ywBusinessDetail) {
			ExceptionHelper.thow(ResultFlagType.MISSING);
		}
		response.setYwBusinessDetail(ywBusinessDetail);
		YwFees ywFees= new YwFees();
		ywFees.setBusiId(id);
		YwFees ywFees1=ywFeesService.selectRefined(ywFees);
		if(ywFees1!=null){
			ywFeesVoMapper.mapper(ywFees1);
			response.setYwFees(ywFees1);
		}
		
		// 查询车辆&车贷信息
		YwBusinessCarExt ywBusinessCarExt = new YwBusinessCarExt();
		ywBusinessCarExt.setBaseWhere();
		ywBusinessCarExt.setRows(1);// 只能返回一条数据
		ywBusinessCarExt.setBusiId(id);
		List<YwBusinessCar> ywBusinessCars = ywBusinessCarService
				.selectByExt(ywBusinessCarExt);
		if (CollectionUtils.isNotEmpty(ywBusinessCars)) {
			YwBusinessCar ywBusinessCar = ywBusinessCars.get(0);
			ywBusinessCarVoMapper.mapper(ywBusinessCar);
			response.setYwBusinessCar(ywBusinessCar);

			String carId = ywBusinessCar.getId();
			
			
			YwBusinessLoanEdit ywBusinessLoanEdit=new YwBusinessLoanEdit();
    		ywBusinessLoanEdit.setBusiId(id);
    		YwBusinessLoanEdit ywBusinessLoanEdit1=ywBusinessLoanEditService.selectRefined(ywBusinessLoanEdit);
			if(ywBusinessLoanEdit1!=null && ywBusinessLoanEdit1.getLoanEditStatus()==LoanEditStatus.YI_SHEN_QING.getCode()){
				ywBusinessLoanEdit1.setCarType(ywBusinessCar.getCarType());
				ywBusinessLoanVoMapper.mapper(ywBusinessLoanEdit1);
				response.setYwBusinessLoanEdit(ywBusinessLoanEdit1);
			}
//			else{
//				// 查询车辆&车贷信息 //只能返回一条数据
//			}
			YwBusinessLoanExt ywBusinessLoanExt = new YwBusinessLoanExt();
			ywBusinessLoanExt.setBaseWhere();
			ywBusinessLoanExt.setRows(1);// 只能返回一条数据
			ywBusinessLoanExt.setBusiId(id);
			ywBusinessLoanExt.setCarId(carId);
			ywBusinessLoanExt.setOrderSql("`CREATED` DESC");
			List<YwBusinessLoan> ywBusinessLoans = ywBusinessLoanService
					.selectByExt(ywBusinessLoanExt);
			if (CollectionUtils.isNotEmpty(ywBusinessLoans)) {
				YwBusinessLoan ywBusinessLoan = ywBusinessLoans.get(0);
				ywBusinessLoan.setCarType(ywBusinessCar.getCarType());
				ywBusinessLoanVoMapper.mapper(ywBusinessLoan);
				response.setYwBusinessLoan(ywBusinessLoan);
			}
		}
		return ApiResponse.success(response);
	}

}
